package com.hippoDocker.security.handler;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.hippoDocker.commons.entities.CommonResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName AccessDenieHandlerImpl
 * @Description TODO spring-security授权过程中出现异常会被封装成AccessDeniedException然后调用AccessDeniedHandler对象的方法去进行异常处理
 * @Author tangxl
 * @Date 2022/7/29 16:34
 **/
@Component
public class AccessDenieHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        CommonResult commonResult = new CommonResult(HttpStatus.HTTP_FORBIDDEN,"无操作权限");
        String json = JSON.toJSONString(commonResult);
        //异常处理
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }
}
